package simpledb;

/**
 * JoinPredicate compares fields of two tuples using a predicate.
 * JoinPredicate is most likely used by the Join operator.
 */
public class JoinPredicate {

    int fieldIndex1  , fieldIndex2 ;
    Predicate.Op op ;

    /**
     * Constructor -- create a new predicate over two fields of two tuples.
     *
     * @param field1 The field index into the first tuple in the predicate
     * @param field2 The field index into the second tuple in the predicate
     * @param op The operation to apply (as defined in Predicate.Op); either
     *   Predicate.Op.GREATER_THAN, Predicate.Op.LESS_THAN, Predicate.Op.EQUAL,
     *   Predicate.Op.GREATER_THAN_OR_EQ, or Predicate.Op.LESS_THAN_OR_EQ
     * @see Predicate
     */
    public JoinPredicate(int field1, Predicate.Op op , int field2) {
        // some code goes here
        this.fieldIndex1 = field1 ;
        this.fieldIndex2 = field2 ;
        this.op = op ;
    }

    /**
     * Apply the predicate to the two specified tuples.
     * The comparison can be made through Field's compare method.
     * @return true if the tuples satisfy the predicate.
     */
    public boolean filter(Tuple t1, Tuple t2) {
        // some code goes here

        Field field1 = t1.getField( fieldIndex1 ) ;
        Field field2 = t2.getField( fieldIndex2 ) ;

        if( field1.getType().equals( Type.INT_TYPE ) ){

            int tupleValue = ((IntField) field1).getValue();
            int orgValue = ((IntField) field2 ).getValue() ;

            if( this.op.equals( Predicate.Op.EQUALS ) ){
                if( tupleValue == orgValue  ){
                    return  true ;
                }
            }else if( this.op.equals( Predicate.Op.GREATER_THAN ) ){
                if( tupleValue > orgValue  ){
                    return  true ;
                }
            }else if( this.op.equals( Predicate.Op.LESS_THAN ) ){
                if( tupleValue < orgValue  ){
                    return  true ;
                }
            }else if( this.op.equals( Predicate.Op.LESS_THAN_OR_EQ ) ){
                if( tupleValue < orgValue ||  tupleValue == orgValue ){
                    return  true ;
                }
            }else if( this.op.equals( Predicate.Op.GREATER_THAN_OR_EQ ) ){
                if( tupleValue > orgValue ||  tupleValue == orgValue ){
                    return  true ;
                }
            }else if( this.op.equals( Predicate.Op.NOT_EQUALS ) ){
                if( tupleValue != orgValue ){
                    return true;
                }
            }
        }

        return false;
    }

}
